const fs = require("fs");
const cheerio = require("cheerio");

const dayjs = require("dayjs");

const url = "./fourInEight.html";
const dataStr = fs.readFileSync(url, "utf-8");

let now = dayjs();
console.log(now);

let dataList = [];

// 获取 html 中的赛程
function getTimeFromHTML() {
  var $ = cheerio.load(dataStr);
  let list = $("#matches-list li");
  list.each((index, item) => {
    const teamA = $(item).find(".matches-team-ni p").eq(0).text();
    const teamB = $(item).find(".matches-team-ni p").eq(1).text();
    const date = $(item).find(".matches-time-date").text();
    const time = $(item).find(".matches-time-hour").text();

    if (teamA && teamB) {
      let obj = {
        title: `${teamA} - ${teamB}`,
        startTime: transTime(date, time),
        endTime: transTime(date, time, "end"),
      };
      dataList.push(obj);
    }
  });

  // 时间处理  20220910T120000Z
  function transTime(date, time, type = "start") {
    let dateArray = date.split("-");
    let month = dateArray[0];
    let day = dateArray[1];
    let timeArray = time.split(":");
    let hour = timeArray[0];
    let min = timeArray[1];
    let realTime = dayjs(`2022-${month}-${day} ${hour}:${min}:00`)
      .subtract(8, "hour")
      .format("YYYYMMDDTHHmm00");
    if (type === "end") {
      realTime = dayjs(`2022-${month}-${day} ${hour}:${min}:00`)
        .subtract(7, "hour")
        .format("YYYYMMDDTHHmm00");
    }
    let res = `${realTime}Z`;
    return res;
  }
}

function writeTemplate() {
  // 写入文件头部
  const headerString = `BEGIN:VCALENDAR\nMETHOD:PUBLISH\nVERSION:2.0\nX-WR-CALNAME:MaxCool 赛程订阅\nX-WR-CALDESC:2022全球LOL总决赛赛程\nX-APPLE-CALENDAR-COLOR:#fe7300\nX-WR-TIMEZONE:Asia/Shanghai\nCALSCALE:GREGORIAN\n\n`;
  fs.writeFileSync("maxcool.ics", headerString, {
    encoding: "utf8",
    flag: "a", // 追加写入同一个文件
  });

  console.log(dataList, " xxxx");

  dataList.forEach((item) => {
    ICSGenFn(item);
  });

  // 写入文件尾部
  const footerString = `END:VCALENDAR`;
  fs.writeFileSync("maxcool.ics", footerString, {
    encoding: "utf8",
    flag: "a", // 追加写入同一个文件
  });
}

//写入文件（文件不存在就创建）
function ICSGenFn(item) {
  let textString = `BEGIN:VEVENT\nTRANSP:TRANSPARENT\nX-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC\nSUMMARY:${item.title}\nDTSTART;VALUE=DATE:${item.startTime}\nDTEND;VALUE=DATE:${item.endTime}\nSEQUENCE:1\nEND:VEVENT\n\n`;

  // 同步写入
  fs.writeFileSync("maxcool.ics", textString, {
    encoding: "utf8",
    flag: "a", // 追加写入同一个文件
  });
}

function init() {
  getTimeFromHTML();
  writeTemplate();
}

init();
